<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\base;

use Yii;
use yii\web\View;
use yii\di\Instance;
use yii\base\Component;
use yii\base\ViewContextInterface;

/**
 * 构建器继承类
 * @property-read string $viewPath 视图文件路径
 * @property-read string|int|null $builderId    当前请求的构建器ID
 * @author cleverstone
 * @since ym2.0
 */
abstract class Builder extends Component implements ViewContextInterface
{
    use Http, BuilderTrait;

    /**
     * @var string 构建器ID
     */
    public $id;

    /**
     * @var string 构建器ID参数
     */
    public $idParam = '__YM2_BUILDER_ID__';

    /**
     * @var string 主布局继承路径
     */
    public $mainPath = '@builder/layouts/main.php';

    /**
     * @var string 局部布局继承路径
     */
    public $partialPath = '@builder/layouts/partial.php';

    /**
     * @var View
     */
    public $_view;

    /**
     * @var int 计数器
     */
    private static $_counter = 0;

    /**
     * 初始化
     */
    public function init()
    {
        if (empty($this->id)) {
            self::$_counter++;

            // 定义当前构建器ID
            $this->id = $this->getName() . self::$_counter;
        }

        $this->_view = Instance::ensure('view', \yii\base\View::class);
    }

    /**
     * 设置构建器身份ID
     * @param string $id
     * @return $this
     */
    public function setId($id)
    {
        $this->id = (string)$id;
        return $this;
    }

    /**
     * 获取当前请求的构建器ID
     * @return string|int|null
     */
    public function getBuilderId()
    {
        return Yii::$app->request->get($this->idParam);
    }

    /**
     * 构建器名称
     * @return string
     */
    abstract public function getName();
}